package com.nt.train.processor;
import com.nt.train.annotation.AutoImport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotationMetadata;
/**
 * https://blog.csdn.net/saygood999/article/details/119330488
 * @AutoImport(value= {XXXX.class})
 * @author hlf
 * @version 1.0
 * @date 2022/8/12 15:20
 */
@Slf4j
public class AopLogRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if(importingClassMetadata.hasAnnotation(AutoImport.class.getName())){
            MergedAnnotations mergedAnnotations = importingClassMetadata.getAnnotations();
            MergedAnnotation mergedAnnotation = mergedAnnotations.get(AutoImport.class);
            if(mergedAnnotation == null){
                return;
            }
            //注解上是否启用
            if( mergedAnnotation.getBoolean("isEnabled")){
                if(log.isInfoEnabled()){
                    log.info(">>>>start auto import bean definition<<<<");
                }
                //获取AutoImport上value配置的class数组
                Class<?>[] values = mergedAnnotation.getClassArray("value");
                for(Class value:values){
                    RootBeanDefinition beanDefinition = new RootBeanDefinition(value);
                    registry.registerBeanDefinition(value.getSimpleName(),beanDefinition);
                }
                if(log.isInfoEnabled()){
                    log.info(">>>>end auto import bean definition<<<<");
                }
            }
        }
    }
}